import { Table, Button, Modal, message } from 'antd';
import React, { useState, useEffect } from 'react'

import { ExclamationCircleFilled } from '@ant-design/icons';

import { BaseGeneraForm } from '../../../components';
import * as college from '../../../api/base/college';

const College: React.FC = () => {
  const [dataSource, setDataSource] = useState<any[]>([])
  const [formData, setFormData] = useState<any>()
  const [open, setOpen] = useState<boolean>(false)
  const [isAdd, setIsAdd] = useState<boolean>(false)

  const formDataConfig = [
    {
      type: 'Input',
      label: '名称',
      fieldName: 'name',
      placeholder: '请输入学院名称'
    },
    {
      type: 'TextArea ',
      label: '描述',
      fieldName: 'desc',
      placeholder: '描述'
    }
  ]

  const getList = async () => {
    const res = await college.list().catch(err => {
      console.log(err)
    })
    if (res.success) {
      setDataSource(res.data)
    }
  }

  const edit = (val: any) => {
    setFormData(val)
    setOpen(true)
  }

  const del = (val: any) => {
    Modal.confirm({
      title: '确定删除',
      icon: <ExclamationCircleFilled />,
      okText: '是',
      cancelText: '否',
      onOk() {
        college.del(val.id).then(res => {
          if (res.success) {
            getList()
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  useEffect(() => {
    getList()
  }, [])

  const columns = [
    {
      title: '学院名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'desc',
      key: 'desc',
    },
    {
      title: '操作',
      key: 'option',
      render: (_: any, record: any) => (
        <>
          <Button type="primary" onClick={() => edit(record)}>编辑</Button>
          <>&nbsp;</>
          <Button type="primary" onClick={() => del(record)}>删除</Button>
        </>
      ),
    },
  ];

  const emitOnFinish = async (val: any, isAdd: boolean) => {
    let res = null
    if (isAdd) {
      res = await college.created(val).catch(err => {
        if (err.data.data.indexOf('key')) {
          message.warning('学院名称重复')
        }
      })
    } else {
      res = await college.update(formData.id, val).catch(err => {
        if (err.data.data.indexOf('key')) {
          message.warning('学院名称重复')
        }
      })
    }
    if (res.success) {
      getList()
      setOpen(false)
      setFormData(null)
    }
  }

  const add = () => { setOpen(true), setIsAdd(true) }
  return (
    <>
      <Button onClick={add}>添加</Button>
      <Table dataSource={dataSource} columns={columns} pagination={{ hideOnSinglePage: true }} rowKey="id" />

      <BaseGeneraForm
        title="学院设置"
        formData={formData}
        isAdd={isAdd}
        open={open}
        onCancel={() => setOpen(false)}
        formDataConfig={formDataConfig}
        footer={null}
        emitOnFinish={emitOnFinish}
      />
    </>

  )
}

export default College

